package cn.chengpengper.seckill.order.infrastructure.repository;

import cn.chengpengper.seckill.common.code.HttpCode;
import cn.chengpengper.seckill.common.exception.SeckillException;
import cn.chengpengper.seckill.order.domain.model.entity.SeckillOrder;
import cn.chengpengper.seckill.order.domain.repository.SeckillOrderRepository;
import cn.chengpengper.seckill.order.infrastructure.mapper.SeckillGoodsOrderMapper;
import cn.chengpengper.seckill.order.infrastructure.mapper.SeckillUserOrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author chengpeng.hu
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SeckillOrderRepositoryImpl implements SeckillOrderRepository {

    private final SeckillGoodsOrderMapper seckillGoodsOrderMapper;

    private final SeckillUserOrderMapper seckillUserOrderMapper;

    @Override
    public boolean saveSeckillOrder(SeckillOrder seckillOrder) {
        if (seckillOrder == null) {
            throw new SeckillException(HttpCode.PARAMS_INVALID);
        }
        log.info("SeckillOrderRepository|saveSeckillOrder|{}", seckillOrder);
        int userResult = seckillUserOrderMapper.saveSeckillOrder(seckillOrder);
        int goodsResult = seckillGoodsOrderMapper.saveSeckillOrder(seckillOrder);
        return userResult == 1 && goodsResult == 1;
    }

    @Override
    public List<SeckillOrder> getSeckillOrderByUserId(Long userId) {
        return seckillUserOrderMapper.getSeckillOrderByUserId(userId);
    }

    @Override
    public List<SeckillOrder> getSeckillOrderByGoodsId(Long goodsId) {
        if (goodsId == null) {
            throw new SeckillException(HttpCode.PARAMS_INVALID);
        }
        return seckillGoodsOrderMapper.getSeckillOrderByGoodsId(goodsId);
    }

    @Override
    public void deleteOrderShardingUserId(Long orderId, Long userId) {
        if (orderId == null || userId == null) {
            throw new SeckillException(HttpCode.PARAMS_INVALID);
        }
        seckillUserOrderMapper.deleteOrder(userId, orderId);
    }

    @Override
    public void deleteOrderShardingGoodsId(Long orderId, Long goodsId) {
        if (goodsId == null || orderId == null) {
            throw new SeckillException(HttpCode.PARAMS_INVALID);
        }
        seckillGoodsOrderMapper.deleteOrder(goodsId, orderId);
    }
}
